<template>
  <view class="container">
    <!-- 天气卡片 -->
    <view class="weather-card" v-if="currentWeather.temp">
      <view class="location">
        <uni-icons type="location-filled" size="20" color="#fff"></uni-icons>
        {{ currentWeather.city }}
      </view>
      <view class="temp">{{ currentWeather.temp }}℃</view>
      <view class="weather">{{ currentWeather.weather }}</view>
    </view>

    <!-- 相关日记 -->
    <view class="related-diary">
      <view class="title">历史相似天气日记（±4℃）</view>
      <view v-for="(item, index) in relatedDiaries" :key="index" class="diary-item" @click="goEdit(item, index)">
        <text>{{ item.date }} | {{ item.weather }} {{ item.temp }}℃</text>
        <text class="content">{{ item.content }}</text>
      </view>
      <view v-if="relatedDiaries.length === 0" class="empty">暂无相关日记</view>
    </view>

    <!-- 浮动按钮 -->
    <view class="float-btn" @click="goEdit()">
      <uni-icons type="plusempty" size="30" color="#fff"></uni-icons>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        currentWeather: {
          temp: null,
          city: '',
          weather: ''
        },
        relatedDiaries: [],
        location: {},
        //替换成自己的key
        key:'yourKey'
      }
    },
    onLoad() {
      this.initWeather()   
    },
    onShow() {
      this.loadDiaries()
    },
    methods: {
      // 跳转编辑页
      goEdit(item = {}, index = -1) {
        const params = {
          // 传递当前天气作为默认值
          ...this.currentWeather,
          // 如果是编辑，传递原内容和索引
          ...item,
          mode: item.date ? 'edit' : 'add',
          index
        }
        uni.navigateTo({
          url: `/pages/diary/edit?data=${encodeURIComponent(JSON.stringify(params))}`
        })
      },
      // 获取设备地理位置
      getLocation() {
        console.log("key,",this.key);
        return new Promise((resolve, reject) => {
          uni.getLocation({
            type: 'wgs84',
            success: (res) => {
              // console.log(res);
              // console.log('位置信息：', res.latitude, res.longitude);
              resolve({
                latitude: res.latitude,
                longitude: res.longitude
              }); // 返回经纬度对象
            },
            fail: (err) => {
              console.error('获取位置失败', err);
              uni.showToast({
                title: '获取位置失败',
                icon: 'none'
              });
              reject(err); // 抛出错误
            }
          });
        });
      },
      // 加载日记并过滤
      loadDiaries() {
        const diaries = uni.getStorageSync('diaries') || []
        this.relatedDiaries = diaries.filter(item => {
          return Math.abs(item.temp - this.currentWeather.temp) <= 4
        })
      },
      // 天气获取方法
      async getWeather(lat, lon) {
        try {
          // 步骤1：获取LocationID
         const locationUrl =
            `https://geoapi.qweather.com/v2/city/lookup?location=${lon},${lat}&key=${this.key}`;
          const locationRes = await uni.request({
            url: locationUrl,
            method: 'GET'
          });

          if (locationRes.data.code !== '200') {
            throw new Error('位置获取失败');
          }

          const locationId = locationRes.data.location[0].id;

          // 步骤2：获取实时天气
          const weatherUrl =
            `https://devapi.qweather.com/v7/weather/now?location=${lon},${lat}&key=${this.key}`;

          const res = await uni.request({
            url: weatherUrl,
            method: 'GET'
          });
          if (res.data.code !== '200') {
            throw new Error('天气数据获取失败');
          }

          return {
            now: {
              temp: res.data.now.temp,
              text: res.data.now.text
            },
            cityInfo: {
              city: locationRes.data.location[0].name,
              // locationId:locationId,
            }
          };
        } catch (error) {
          uni.showToast({
            title: error.message,
            icon: 'none'
          });
          return {};
        }
      },

      // 修改后的初始化方法
      async initWeather() {
        try {
          uni.showLoading({
            title: '获取天气中'
          });

          const location = await this.getLocation();
          const weatherRes = await this.getWeather(location.latitude, location.longitude);

          this.currentWeather = {
            temp: weatherRes.now.temp,
            city: weatherRes.cityInfo.city,
            // locationId: weatherRes.cityInfo.locationId,
            weather: weatherRes.now.text
          };
          this.loadDiaries()
        } catch (error) {
          console.error(error);
        } finally {
          uni.hideLoading();
        }
      }
    }
  }
</script>
<style scoped>
  /* 容器样式 */
  .container {
    padding: 30rpx;
    background: #f8f9fa;
    min-height: 100vh;
  }

  /* 天气卡片 */
  .weather-card {
    padding: 40rpx;
    background: #fff;
    border-radius: 16rpx;
    box-shadow: 0 8rpx 30rpx rgba(143, 168, 191, 0.1);
    margin-bottom: 30rpx;
    position: relative;
    overflow: hidden;
  }

  .weather-card::after {
    content: '';
    position: absolute;
    top: -50rpx;
    right: -50rpx;
    width: 150rpx;
    height: 150rpx;
    background: rgba(163, 207, 187, 0.1);
    border-radius: 50%;
  }

  .location {
    font-size: 28rpx;
    color: #6c757d;
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
  }

  .temp {
    font-size: 72rpx;
    color: #2c3e50;
    font-weight: 300;
    margin: 10rpx 0;
  }

  .weather {
    font-size: 32rpx;
    color: #95a5a6;
  }

  /* 日记列表 */
  .related-diary .title {
    font-size: 28rpx;
    color: #7f8c8d;
    margin-bottom: 30rpx;
    padding-left: 20rpx;
    position: relative;
  }

  .related-diary .title::before {
    content: '';
    position: absolute;
    left: 0;
    /* 移动至父元素的50%处 */
    top: 50%;
    /* 向上移动自身的50%*/
    transform: translateY(-50%);
    width: 8rpx;
    height: 32rpx;
    background: #a3cfbb;
    border-radius: 4rpx;
  }

  .diary-item {
    background: #fff;
    padding: 30rpx;
    border-radius: 12rpx;
    margin-bottom: 20rpx;
    /* 水平偏移量，垂直偏移量，模糊半径*/
    box-shadow: 0 4rpx 20rpx rgba(143, 168, 191, 0.05);
  }

  .diary-item text:first-child {
    color: #2c3e50;
    font-size: 26rpx;
    display: block;
    margin-bottom: 15rpx;
  }

  .diary-item .content {
    color: #7f8c8d;
    font-size: 28rpx;
    line-height: 1.6;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
  }

  .empty {
    text-align: center;
    color: #bdc3c7;
    font-size: 28rpx;
    padding: 40rpx 0;
  }

  /* 浮动按钮 */
  .float-btn {
    position: fixed;
    right: 40rpx;
    bottom: 80rpx;
    width: 100rpx;
    height: 100rpx;
    background: #a3cfbb;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 8rpx 20rpx rgba(163, 207, 187, 0.3);
    transition: transform 0.2s;
  }

  .float-btn:active {
    transform: scale(0.95);
  }
</style>